package core

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"suitbim.com/media/middleware"
)

type HttpServer struct {
	router *gin.Engine
}

// NewHttpServer Start 开启一个http服务
func NewHttpServer(mode string) *HttpServer {
	// 如果是生产模式则设置对应的模式
	if mode == "pro" {
		gin.SetMode(gin.ReleaseMode)
	} else {
		gin.SetMode(gin.DebugMode)
	}
	router := gin.Default()
	router.Use(middleware.Cors()) // 使用跨域中间件
	return &HttpServer{
		router: router,
	}
}

// StartNoRouterGroup 开启无需认证路由组
func (o *HttpServer) StartNoRouterGroup(relativePath string, routerMap map[string]map[string]any) {
	routerGroup := o.router.Group(relativePath)
	{
		// 路由列表，动态传入
		for key, value := range routerMap {

			// 获取请求方法
			method := value["method"]
			handle := value["handle"].(func(*gin.Context))
			if method == "GET" {
				routerGroup.GET(key, handle)
			} else if method == "POST" {
				routerGroup.POST(key, handle)
			}
		}
	}
}

func (o *HttpServer) Run(port int) {
	G.Log.Infof("Http server has started at port: %d", port)
	o.router.Run(fmt.Sprintf(":%d", port))
}
